// 全选/取消全选功能
function toggleSelectAll() {
    const selectAllCheckbox = document.getElementById('selectAll');
    const checkboxes = document.querySelectorAll('.title-checkbox');
    checkboxes.forEach(checkbox => {
        checkbox.checked = selectAllCheckbox.checked;
    });
    toggleBatchDeleteButton();
}

// 页面加载完成后添加事件监听器
document.addEventListener('DOMContentLoaded', function() {
    // 为全选框添加事件监听
    const selectAllCheckbox = document.getElementById('selectAll');
    if (selectAllCheckbox) {
        selectAllCheckbox.addEventListener('change', toggleSelectAll);
    }
    
    // 为所有复选框添加事件监听
    const checkboxes = document.querySelectorAll('.title-checkbox');
    checkboxes.forEach(checkbox => {
        checkbox.addEventListener('change', toggleBatchDeleteButton);
    });
    
    // 为批量删除按钮添加事件监听
    const batchDeleteBtn = document.getElementById('batchDeleteBtn');
    if (batchDeleteBtn) {
        batchDeleteBtn.addEventListener('click', submitBatchDelete);
    }
    
    // 初始化状态切换功能
    setupStatusToggleButtons();
});

// 根据选中状态启用/禁用批量删除按钮
function toggleBatchDeleteButton() {
    const checkboxes = document.querySelectorAll('.title-checkbox:checked');
    const batchDeleteBtn = document.getElementById('batchDeleteBtn');
    batchDeleteBtn.disabled = checkboxes.length === 0;
}

// 提交批量删除表单
function submitBatchDelete() {
    const checkboxes = document.querySelectorAll('.title-checkbox:checked');
    if (checkboxes.length === 0) {
        createNotification('请先选择要删除的标题', 'error');
        return;
    }
    
    if (confirm('确定要删除选中的标题吗？')) {
        const formData = new FormData();
        checkboxes.forEach(checkbox => {
            formData.append('title_ids', checkbox.value);
        });
        
        fetch('/admin/titles/batch-delete', {
            method: 'POST',
            headers: {
                'X-Requested-With': 'XMLHttpRequest'
            },
            body: formData
        })
        .then(response => response.json())
        .then(data => {
            if (data.success) {
                // 添加删除动画效果
                checkboxes.forEach(checkbox => {
                    const row = checkbox.closest('tr');
                    row.style.transition = 'all 0.3s ease';
                    row.style.height = row.offsetHeight + 'px';
                    
                    // 触发重排
                    void row.offsetHeight;
                    
                    row.style.height = '0';
                    row.style.opacity = '0';
                    row.style.padding = '0';
                    row.style.margin = '0';
                    
                    // 动画结束后移除元素
                    setTimeout(() => {
                        row.remove();
                        // 如果所有行都被删除，更新全选状态
                        if (document.querySelectorAll('tbody tr').length === 0) {
                            document.getElementById('selectAll').checked = false;
                            toggleBatchDeleteButton();
                        }
                    }, 300);
                });
                
                // 清空选中状态并禁用批量删除按钮
                document.getElementById('selectAll').checked = false;
                toggleBatchDeleteButton();
                
                createNotification(data.message, 'success');
            } else {
                createNotification(data.message, 'error');
            }
        })
        .catch(error => {
            createNotification('删除失败，请重试', 'error');
        });
    }
}

// 单个删除功能
document.addEventListener('click', function(event) {
    if (event.target.classList.contains('delete-btn')) {
        const button = event.target;
        const titleId = button.getAttribute('data-id');
        const titleName = button.getAttribute('data-name');
        
        if (confirm(`确定要删除标题 "${titleName}" 吗？`)) {
            const formData = new FormData();
            
            fetch(`/admin/titles/delete/${titleId}`, {
                method: 'POST',
                headers: {
                    'X-Requested-With': 'XMLHttpRequest'
                },
                body: formData
            })
            .then(response => response.json())
            .then(data => {
                if (data.success) {
                    // 添加删除动画效果
                    const row = button.closest('tr');
                    row.style.transition = 'all 0.3s ease';
                    row.style.height = row.offsetHeight + 'px';
                    
                    // 触发重排
                    void row.offsetHeight;
                    
                    row.style.height = '0';
                    row.style.opacity = '0';
                    row.style.padding = '0';
                    row.style.margin = '0';
                    
                    // 动画结束后移除元素
                    setTimeout(() => {
                        row.remove();
                        // 如果所有行都被删除，更新全选状态
                        if (document.querySelectorAll('tbody tr').length === 0) {
                            document.getElementById('selectAll').checked = false;
                            toggleBatchDeleteButton();
                        }
                    }, 300);
                    
                    createNotification(data.message, 'success');
                } else {
                    createNotification(data.message, 'error');
                }
            })
            .catch(error => {
                createNotification('删除失败，请重试', 'error');
            });
        }
    }
});

// 通知函数
function createNotification(message, type = 'info') {
    // 创建通知元素
    const notification = document.createElement('div');
    notification.className = 'notification ' + type;
    notification.textContent = message;
    
    // 设置样式
    notification.style.position = 'fixed';
    notification.style.top = '20px';
    notification.style.right = '20px';
    notification.style.padding = '15px 20px';
    notification.style.borderRadius = '5px';
    notification.style.color = 'white';
    notification.style.fontWeight = 'bold';
    notification.style.zIndex = '9999';
    notification.style.opacity = '0';
    notification.style.transition = 'all 0.3s ease';
    notification.style.boxShadow = '0 2px 10px rgba(0, 0, 0, 0.2)';
    
    // 根据类型设置背景颜色
    if (type === 'success') {
        notification.style.backgroundColor = '#2ecc71';
    } else if (type === 'error') {
        notification.style.backgroundColor = '#e74c3c';
    } else if (type === 'warning') {
        notification.style.backgroundColor = '#f39c12';
    } else {
        notification.style.backgroundColor = '#3498db';
    }
    
    // 添加到页面
    document.body.appendChild(notification);
    
    // 触发动画
    setTimeout(() => {
        notification.style.opacity = '1';
        notification.style.top = '20px';
    }, 10);
    
    // 3秒后消失
    setTimeout(() => {
        notification.style.opacity = '0';
        notification.style.top = '-100px';
        
        // 动画结束后移除元素
        setTimeout(() => {
            document.body.removeChild(notification);
        }, 300);
    }, 3000);
}

// 状态切换功能
function setupStatusToggleButtons() {
    document.querySelectorAll('.toggle-status-btn').forEach(btn => {
        btn.addEventListener('click', async (e) => {
            e.preventDefault();
            const titleId = btn.getAttribute('data-id');
            const currentStatus = btn.getAttribute('data-status') === 'true';
            const targetStatus = !currentStatus;
            const confirmText = targetStatus ? '确定要启用此标题吗？' : '确定要禁用此标题吗？';
            
            if (confirm(confirmText)) {
                // 禁用按钮并显示加载状态
                btn.disabled = true;
                btn.textContent = '处理中...';
                
                try {
                    // 使用Fetch API发送请求
                    const response = await fetch(`/admin/titles/toggle-status/${titleId}`, {
                        method: 'POST',
                        headers: {
                            'X-Requested-With': 'XMLHttpRequest',
                            'Content-Type': 'application/json'
                        },
                        body: JSON.stringify({ new_status: targetStatus })
                    });
                    
                    // 解析JSON响应
                    const result = await response.json();
                    
                    if (result.success) {
                        // 使用后端返回的new_status更新按钮的data-status属性
                    btn.setAttribute('data-status', result.new_status.toString());
                    
                    // 更新按钮样式和文本
                    btn.className = 'btn btn-xs ' + (result.new_status ? 'btn-warning' : 'btn-success') + ' toggle-status-btn';
                    btn.textContent = result.new_status ? '禁用' : '启用';
                    
                    // 更新状态显示文本
                    const statusSpan = btn.previousElementSibling;
                    if (statusSpan) {
                        statusSpan.textContent = result.new_status ? '启用' : '禁用';
                        statusSpan.style.color = result.new_status ? '#2ecc71' : '#e74c3c';
                    }
                    
                    // 恢复按钮可用状态
                    btn.disabled = false;
                        
                    createNotification(result.message || '状态更新成功', 'success');
                    } else {
                        // 恢复按钮状态
                        btn.disabled = false;
                        btn.textContent = targetStatus ? '启用' : '禁用';
                        // 显示错误通知
                        createNotification(result.message || '状态更新失败', 'error');
                    }
                } catch (error) {
                    // 恢复按钮状态
                    btn.disabled = false;
                    btn.textContent = targetStatus ? '启用' : '禁用';
                    // 显示错误通知
                    createNotification('状态切换失败，请稍后重试', 'error');
                }
            }
        });
    });
}